// @ts-nocheck
/* api */
import{ getPoolList, getTaskPoolHeadInfos, getTaskPoolListInitData, getAllFields, getCurrentAllTaskTypeList } from '@src/api/TaskApi'
/* business */
import BizListViewTask from '@src/component/business/BizListView/Impl/BizListViewTask/BizListViewTask.tsx'
/* computed */
import TaskPoolListComputed from '@src/modules/task/taskTypes/taskPool/TaskPoolListComputed'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
import { TaskFieldNameMappingEnum, FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum'
import TableNameEnum from '@model/enum/TableNameEnum.ts';
/* entity */
import Field from '@model/entity/Field'
import EsTask from '@model/entity/EsTask'
import TaskType from '@model/entity/TaskType'
/* model */
import { getTaskPoolInitDataResult } from '@model/param/out/Task'
import { getColumnFields, getAdvancedFields } from '@src/modules/task/taskTypes/taskPool/fields'
import { isCalendar } from '@src/util/CalendarUtil';
import * as TaskApi from '@src/api/TaskApi.ts';
import { commonUseItemType } from '@src/component/AdvancedSearch/advancedSearch'
import { storageSet, storageGet } from '@src/util/storageV2';
import _, { isEmpty, cloneDeep } from 'lodash';
import { setServerCach, getServerCach } from '@src/util/serverCach'
/* service */
import {
  isAttachmentFiled,
  isPlanTimeField,
  isPlanStartTimeField,
  isPlanEndTimeField,
  isSystemFiled,
  isTaskNoField,
} from '@service/FieldService'

import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { dayTimeStart } from 'pub-bbx-utils';
import { t } from '@src/locales'

class TaskPoolListMethods extends TaskPoolListComputed {
  public computedListPxArray(){
    let tableHeaderTypeContainer_ = this.$refs.tableHeaderTypeContainer?.offsetHeight;
    let padding = [tableHeaderTypeContainer_, 24, 10, 16, 16]
    return padding;
  }
  public changePackUpLocal(){
    this.changePackUp()
  }
  /**
   * @description 接受工单
   */ 
  public async acceptTask(row: EsTask): void {
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('ACCEPT_TASK'));

    const templateId: string = row?.templateId || ''
    // const taskType: TaskType = this.taskTypesMap[templateId] || { field: [] }
    // const fields: Field[] = taskType?.field || []

    const fields = await this.getRowFields(templateId) || [];
    
    for (let field of fields) {
      if (isPlanTimeField(field)) {
        this.currentAcceptTaskPlanTimeField = field;
        continue;
      } else if(isPlanStartTimeField(field)){
        this.currentAcceptTaskPlanStartTimeField = field;
        continue;
      } else if(isPlanEndTimeField(field)){
        this.currentAcceptTaskPlanEndTimeField = field;
        continue;
      }
    }
    
    this.currentAcceptTask = row

    this.$nextTick(() => {
      
      let action = 'acceptFromPool'
      if(isCalendar){
        this.CalendarPlanTimeDialogComponent?.beforeOpenForAccept(action);
      }else{
        this.PlanTimeDialogComponent?.beforeOpenForAccept(action);
      }
    })
  }
  
  // 不同工单不同字段
  public getRowFields(templateId: string): Promise {
    return getAllFields({typeId: templateId,tableName: TableNameEnum.Task,isFromSetting: false});
  }

  /* 计划开始时间 */
  public getPlanStartTime(fields: Field[], row: EsTask) {
    let planStartTimeField = fields.filter(f => f.fieldName === 'planStartTime')[0];
    let { dateType } = planStartTimeField?.setting || {};
    let { isEncryptPlanTime, planStartTime } = row;

    if (planStartTime) {
      if (isEncryptPlanTime) return '***';
      // 计划时间格式为日期时需格式化
      if (dateType == 'date') return +dayTimeStart(planStartTime);
      return planStartTime;
    }
    return ''
  }

  /* 计划完成时间 */
  public getPlanEndTime(fields: Field[], row: EsTask) {
    let planEndTimeField = fields.filter(f => f.fieldName === 'planEndTime')[0];
    let { dateType } = planEndTimeField?.setting || {};
      let { isEncryptPlanTime, planEndTime } = row;
      if (planEndTime) {
        if (isEncryptPlanTime) return '***';
        // 计划时间格式为日期时需格式化
        if (dateType == 'date') return planEndTime.slice(0, 10);
        return planEndTime;
      }
      return '';
  }
  
  public goNextStep(action, row: EsTask) {
    TaskApi[action]({taskId:row.id}).then(res => {
      if (res.success) {
        window.location.href = `${this.$resourcePrefix}/task/view/${row.id}`;
      } else {
        this.$platform.alert(res.message);
      }
    })
  }
  /**
   * @description: 批量转派事件
   * @return {void}
   */  
  public async batchReAllotTaskHandler(): Promise<void> {
    const validated = this.selectedTaskDataValidate()
    if (!validated) return

    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('BATCH_RE_ALLOT'));
    
    // @ts-ignore
    this.TaskTransferComponent?.openSendMessageDialog()
  }
  
  /**
   * @description 构建高级搜索列
   */
  public buildAdvancedColumns() {
    this.advanceSearchColumns = this.advancedSearchColumnsFilterHandler([
      ...this.getAdvancedFields(this),
    ])
  }
  
  /**
   * @description: 获取高级搜索字段列表
   * @param {BizListViewTask} vm 当前实例
   * @return {Field[]} 高级搜索字段列表
   */  
  public getAdvancedFields(vm: BizListViewTask): Field[] {
    // 基础版过滤产品、曾打印字段
    let advancedFields = getAdvancedFields(vm).filter(field => field.show)
    if (this.isBasicEditionHideProduct) {
      advancedFields = advancedFields.filter(field => field.fieldName !== 'product')
    }
    if (this.isBasicEditionHidePrintTask) {
      advancedFields = advancedFields.filter(field => field.fieldName !== 'oncePrinted')
    }

    return advancedFields
  }
  
  /**
   * @description: 获取表格列字段列表
   * @param {BizListViewTask} vm 当前实例
   * @return {Field[]} 表格列字段列表
   */  
  public getColumnFields(vm: BizListViewTask): Field[] {
    // 基础版过滤产品、曾打印字段
    let columnFields = getColumnFields(vm);
    if (this.isBasicEditionHideProduct) {
      columnFields = columnFields.filter(field => field.fieldName !== 'product')
    }
    if (this.isBasicEditionHidePrintTask) {
      columnFields = columnFields.filter(field => field.fieldName !== 'oncePrinted')
    }

    return columnFields
  }
  
  /** 
   * @description 获取属性
  */
  public getAttributes() {
    const classNames: string[] = [ComponentNameEnum.TaskPoolList, 'common-list-container__v2']
    
    return {
      class: classNames,
      directives: [
        // {
        //   name: 'loading',
        //   value: this.loading
        // }
      ]
    }
  }
  
  public fetchTableListData() {
    const params = {
      ...this.searchParams,
      ...this.advancedSearchModel,
    }
    // 地图模式时触发地图模式搜索
    this.$nextTick(() => {
      if (this.mapShow && this.$refs.taskMap) {
        this.$refs.taskMap.init()
      }
    })
    
    this.fetchTaskList(params, getPoolList)
  }
  
  /**
   * @description: 获取初始化数据
   * @return {Promise<void>}
   */  
  public async fetchInitData(): Promise<void> {
    this.loading = true
    
    return (
      getTaskPoolListInitData()
        .then(async (result: getTaskPoolInitDataResult) => {
          this.initData = result
          this.taskTypes1 = result?.taskTypeList || []
          this.taskConfig = result?.taskConfig || null
          this.auth = result?.authorities || {}
        })
        .catch(err => {
          console.error(err)
        })
    )
  }

  public taskTypes1:any = []
  
  /**
   * @description: 获取工单池统计信息
   * @return {Promise<void>}
   */  
  public async fetchTaskPoolInfos(): Promise<void> {
    return (
      getTaskPoolHeadInfos()
        .then((result) => {
          this.taskPoolCountInfo = result
        })
        .catch(err => {
          console.error(err)
        })
    )
  }
  
  /**
   * @description: 初始化工单类型所有字段
   * 工单类型变化之后的事件
   * 1. 获取工单类型字段
   * 2. 构建高级搜索列
   * @return {void}
   */  
  public async initializeTaskTypeAllFields(): Promise<void> {
    // 获取工单类型字段
    await this.fetchTaskFields()
    // 构建高级搜索列
    this.buildAdvancedColumns()
  }
  
  public searchOverTimeTasks(isOverTime: boolean = true) {
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams(`${isOverTime ? 'PENDING_TASK_CARD' : 'OVERTIME_TASK_CARD'}`));

    // exceptionType： 2：超时 1: 暂停 0：默认
    this.searchParams.exceptionType = isOverTime ? 2 : 0
    this.searchParams.pageNum = 1
    this.search()
  }
  
  public toggleMapShow(show: boolean = true) {
    this.mapShow = show
    // 地图模式时默认收起
    show && this.packUp ? this.changePackUp() : ''
  }
  
  public refresh() {
    this.loading = true
    setTimeout(async() => {
      this.BizTableComponent?.outsideClearSelection()
      this.multipleSelection = []
      await this.search()
      this.fetchTaskPoolInfos()
      // this.loading = false
    }, 1000)
  }

  // 调整计划时间组件确认 callback func
  planTimeConfirm() {
    this.refresh()
    let fromId = window?.frameElement?.getAttribute('id');
    
    openAccurateTab({
      type: PageRoutesTypeEnum.PageTaskView,
      key: this.currentAcceptTask?.id,
      titleKey: this.currentAcceptTask?.taskNo,
      fromId
    })
  }

  /**
   * 高级搜索
   * @param searchModel
   */
  public handleAdvancedSearch(searchModel: any = {}){
    this.advancedSearchModel = searchModel;
    this.search();
  }

  /**
   * 常用字段切换
   * @param {*} fieldName
   * @param {*} isChecked
   */
  public changeCommonUse({fieldName, isChecked}: commonUseItemType){
    const inCommonUseSet = new Set(this.inCommonUse)
    if(isChecked){
      inCommonUseSet.add(fieldName)
    }else {
      inCommonUseSet.delete(fieldName);
    }
    this.inCommonUse = Array.from(inCommonUseSet);
    const storageKey = 'advanced-search-commonUse';
    const storageData = {
      [storageKey]: this.inCommonUse
    }
    storageSet('taskPoolList', JSON.stringify(storageData))
    setServerCach('taskPoolList', storageData, 'task', 'taskPoolList')
  }

  /**
   * 恢复常用字段
   */
  public async recoverCommonUse(){
    try {
      let data = storageGet('taskPoolList') || '{}';
      if(data === '{}'){
        data = await getServerCach('taskPoolList', {}, 'task', 'taskPoolList') || {}
        data = JSON.stringify(data)
      }
      data = JSON.parse(data)
      const storageKey = 'advanced-search-commonUse';
      this.inCommonUse = data[storageKey] || [];
    } catch (error) {
      console.error('获取常用字段 recoverCommonUse', error);
      return Promise.reject(error)
    }
  }

  public chooseView(_v) {
    this.currentTaskType = { name:'全部', id:undefined, templateId:undefined }; // 重置 工单类型
    this.searchParams.keyword = ''; // 重置 keyword
    this.searchParams.pageNum = 1;

    this.currentView = this.genViewport(_v); // 视图设为当前视图
    if(this.currentView?.shortcutConditions){
      // 外面固定条件截取
      this.changeAdvancedSearchCommonForm(this.currentView.shortcutConditions);
    }
    this.viewportSearchModel = this.currentView?.searchModel || [];
  }

  /**
   * 从高级筛选中修改常用搜索字段
   */
  public changeAdvancedSearchCommonForm(formData){
    const { taskType } = formData;

    if(taskType !== this.currentTaskType?.id){
      // 切换工单字段 需要重新获取字段等
      const type = this.taskTypes.find(item => item.id === taskType);
      this.changeTaskType(type || {id: taskType}, false) // 粗略兼容工单类型没有的情况
      return;
    }
  }

  // 处理视图
  public genViewport(_v){
    if(!_v || !_v.searchModel) return null
    const viewport = cloneDeep(_v);
    if(viewport?.searchModel[0]?.fieldName === 'taskCommonSearch'){
      // 外面固定条件截取
      const formData = viewport.searchModel.shift();
      viewport.shortcutConditions = formData.value;
    }
    return viewport
  }

  // 生成快捷条件
  public genShortcutConditions() {
    return {
      taskType: this.currentTaskType?.id || '',
    }
  }

  /**
   * 视图保存成功 更新选中视图
   * @param {Object} _v 视图信息
   */
  public handleViewportSave(_v){
    if(!_v) return;
    this.chooseView(_v); // 选中当前视图
    this.$refs.viewportListRef?.refresh(_v.viewId); // 刷新视图列表 并选中
  }

  /**
   * 视图列表 点击 编辑/新建
   */
  public editViewByViewport(_v){
    const viewport = this.genViewport(_v);
    this.shortcutConditions = viewport?.shortcutConditions || this.genShortcutConditions();
    this.getQuickConditionTaskTypeName(true, this.shortcutConditions?.taskType)
    this.$refs.advancedSearchModalRef.open(viewport);
  }

  /**
   * 高级筛选 点击 新建
   */
  public createViewBySearchModel(searchModel) {
    this.shortcutConditions = this.genShortcutConditions();
    this.getQuickConditionTaskTypeName(false)
    this.$refs.advancedSearchModalRef.open({ searchModel })
  }

  /**
   * 高级筛选 点击 保存
   */
  public updateViewBySearchModel(searchModel) {
    const viewportData = {
      ...this.currentView,
      searchModel,
    }
    this.shortcutConditions = this.genShortcutConditions();
    this.$refs.advancedSearchModalRef.open(viewportData)
  }

  // 保存视图之前，存入外部固定条件到视图中
  public beforeSaveView(viewport) {
    const value = viewport?.shortcutConditions || this.genShortcutConditions();
    
    return [
      {fieldName: 'taskCommonSearch', operator: '', value },
    ]
  }

  // 获取视图快捷条件的工单类型名称
  public getQuickConditionTaskTypeName(isEdit, taskType) {
    if (isEdit) {
      const type = this.taskTypes.find(item => item.id === taskType);
      this.quickConditionTaskTypeName = type?.name || t('common.base.all')
    } else {
      this.quickConditionTaskTypeName = this.currentTaskType?.name || t('common.base.all')
    }
  }
}

export default TaskPoolListMethods
